package com.jqkb.pages;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jqkb.R;
import com.jqkb.adapters.SelectTargetAdapter;
import com.jqkb.service.ActionService;
import com.jqkb.service.UserService;
import com.jqkb.service.bean.User;
import com.jqkb.service.util.BeanCallBack;
import com.jqkb.service.util.CallBack;
import com.jqkb.service.util.Converter;
import com.jqkb.service.util.ListCallBack;
import com.jqkb.service.util.SimpleApi;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.jqkb.utils.Constant;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class SelectTargetActivity extends AppCompatActivity {


    RecyclerView recyclerView;
    LinearLayoutManager layoutManager;
    SelectAdapter mAdapter;
    private Button fab;


    List<Object> users;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.target_list_layout);
        users = new ArrayList<>();


        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);


        UserService service = SimpleApi.create(UserService.class);
        Call<ResponseBody> call = service.listReportingUser();
        Converter.convert(Object.class, call, new CallBack<Object>() {

            @Override
            public void onSuccess(Object o, JsonNode jsonNode) {

                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);


                JsonNode data = jsonNode.path("data");
                Iterator<JsonNode> iterator = data.iterator();

                while (iterator.hasNext()) {
                    JsonNode next = iterator.next();
                    Iterator<JsonNode> nextIterator = next.iterator();
                    while (nextIterator.hasNext()) {
                        JsonNode childNode = nextIterator.next();
                        User user = objectMapper.convertValue(childNode, User.class);
                        users.add(user);
                    }

                    if (iterator.hasNext()) {
                        users.add(-1);
                    }

                }

                mAdapter = new SelectAdapter();
                recyclerView.setAdapter(mAdapter);


            }


            @Override
            public void onError(Call<ResponseBody> response) {
            }

            @Override
            public void onFail(boolean success, int code, String message, JsonNode data) {

                Toast.makeText(SelectTargetActivity.this, message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNetworkFail(Call<ResponseBody> jsonNode) {
                Toast.makeText(SelectTargetActivity.this, "网路连接失败", Toast.LENGTH_SHORT).show();
            }
        });


        this.fab = (Button) findViewById(R.id.fab);

        this.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ArrayList<String> list = new ArrayList<>();


                for (Object user : users) {

                    if (user instanceof User) {

                        if (((User) user).isChecked()) {

                            Long targetId = ((User) user).getId();
                            list.add(targetId.toString());
                        }
                    }
                }


                if (list.isEmpty()) {
                    Toast.makeText(SelectTargetActivity.this, "选择上报目标", Toast.LENGTH_SHORT).show();
                    return;
                }


                Intent intent = getIntent();
                intent.putStringArrayListExtra("users", list);
                setResult(Constant.OPEN_SELECT_TARGET, intent);
                finish();


            }
        });
    }


    public class SelectAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
            View itemView;
            if (type == 0) {
                itemView = new View(viewGroup.getContext());
                itemView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 20));
                itemView.setBackgroundColor(Color.GRAY);

            } else {
                itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.select_target_list_item, viewGroup, false);
            }

            return new ListItemViewHolder(itemView);
        }


        //绑定界面，设置监听
        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int i) {
            //设置条目状态
            Object o = users.get(i);

            if (!(o instanceof User)) {

                return;
            }

            final User user = (User) o;
            ((ListItemViewHolder) holder).itemView.setTag(user);
            ((ListItemViewHolder) holder).mainTitle.setText(user.getName());
            ((ListItemViewHolder) holder).checkBox.setChecked(user.isChecked());
            ((ListItemViewHolder) holder).checkBox.setClickable(false);


            //条目view的监听
            ((ListItemViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    User user = (User) v.getTag();
                    user.setChecked(!user.isChecked());
                    notifyDataSetChanged();
                }
            });


        }

        @Override
        public int getItemViewType(int position) {

            if ((users.get(position) instanceof User)) {
                return 1;
            } else {
                return 0;
            }
        }

        @Override
        public int getItemCount() {
            return users.size();
        }

        public class ListItemViewHolder extends RecyclerView.ViewHolder {
            //ViewHolder
            CheckBox checkBox;
            TextView mainTitle;

            ListItemViewHolder(View view) {
                super(view);
                this.mainTitle = (TextView) view.findViewById(R.id.name_tv);
                this.checkBox = (CheckBox) view.findViewById(R.id.checkBox);

            }
        }
    }


}